package com.yfw.maple_leaf_store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yfw.maple_leaf_store.common.BaseContext;
import com.yfw.maple_leaf_store.common.CustomException;
import com.yfw.maple_leaf_store.domain.*;
import com.yfw.maple_leaf_store.dto.OrderCollectDto;
import com.yfw.maple_leaf_store.mapper.OrdersMapper;
import com.yfw.maple_leaf_store.mapper.UserMapper;
import com.yfw.maple_leaf_store.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.ThresholdingOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author: yfw
 * @date: 2022/6/14 19:41
 * com.yfw.maple_leaf_store.service.impl
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrderService {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private GoodsService goodsService;

    /**
     * 获取卖家名称
     *
     * @param sellerWrapper
     * @param sellGoodsWrapper
     * @param item
     * @return
     */
    public String getSellerName(LambdaQueryWrapper<User> sellerWrapper, LambdaQueryWrapper<Goods> sellGoodsWrapper, ShoppingCart item) {
        //根据商品表找出卖家id，再根据卖家id找到卖家名称
        sellGoodsWrapper.eq(Goods::getId, item.getGid());
        Goods sellGoods = goodsService.getOne(sellGoodsWrapper);
        sellerWrapper.eq(User::getId, sellGoods.getSid());
        String seller_name = userService.getOne(sellerWrapper).getName();
        return seller_name;
    }

    /**
     * 用户下单
     * 前台只需传入默认地址id即可
     * 四表联查-购物车，用户表，地址管理表
     *
     * @param orderCollectDto
     */
    @Transactional
    public void submit(OrderCollectDto orderCollectDto) {

        //获得当前用户id
        Long userId = BaseContext.getCurrentId();
//        Long userId = Long.valueOf("1538364171261296641");//测试
        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(ShoppingCart::getId, orderCollectDto.getIds());
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);//可能有多个购物车同时生成一个订单，也有可能一个购物车生成一个订单
        if (orderCollectDto.getIds() == null || shoppingCarts.size() == 0) {
            throw new CustomException("购物车为空，不能下单");
        }
        log.info("购物车信息:{}",shoppingCarts);
        //查询用户数据
        User user = userService.getById(userId);
        //查询地址数据
        Long addressBookId = orderCollectDto.getAddressBook().getId();//地址栏管理默认id属性
        AddressBook addressBook = addressBookService.getById(addressBookId);//根据前端传来的地址管理查询一次
        if(addressBook == null){
            throw new CustomException("用户地址信息有误，不能下单");//自定义异常
        }
        long orderId = IdWorker.getId();//订单号--md插件提供一组id的自动生成

        AtomicInteger amount = new AtomicInteger(0);//原子操作整数类型，在高并发中保证线程安全

        //为了插入订单详细信息，需要查询出具体商品基本信息（名称、数量、单价等） orderdetail
        List<OrderDetail> orderDetailList = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOid(orderId);//订单id
            orderDetail.setNumber(item.getNumber());
            orderDetail.setGid(item.getGid());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            //根据商品表找出卖家id，再根据卖家id找到卖家名称
            //String seller_name = getSellerName(sellerWrapper,sellGoodsWrapper,item);
            LambdaQueryWrapper<User> sellerWrapper = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<Goods> sellGoodsWrapper = new LambdaQueryWrapper<>();//用于查询卖家名称
            sellGoodsWrapper.eq(Goods::getId, item.getGid());
            Goods sellGoods = goodsService.getOne(sellGoodsWrapper);
            sellerWrapper.eq(User::getId, sellGoods.getSid());
            String seller_name = userService.getOne(sellerWrapper).getName();
            orderDetail.setSellerName(seller_name);
            //计算每个购物车中的总价
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());//从零开始，线程安全的累加
            return orderDetail;
        }).collect(Collectors.toList());
        Orders orders = new Orders();//将其汇总到订单表中
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setCheckoutTime(LocalDateTime.now());//结账时间
        orders.setStatus(2);
        orders.setRemark(orderCollectDto.getRemark());
        orders.setAddressBookId(addressBookId);
        //BigDecimal()用来对超过16位有效位的数进行精确的运算
        orders.setAmount(new BigDecimal(amount.get()));//总金额，防止浮点数计算时精度丢失
        orders.setUid(userId);
        orders.setNumber(String.valueOf(orderId));//订单编号
        orders.setUname(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getDetail() == null ? "" : addressBook.getDetail()));//详细地址
        this.save(orders);//生成订单信息并插入
        log.info("{}",orders);
        //向订单明细表插入数据，批量插入多条数据
        orderDetailService.saveBatch(orderDetailList);
        log.info("{}",orderDetailList);

        //清空被生成订单的购物车
        shoppingCartService.remove(wrapper);
    }
//    @Transactional
//    public void submit(List<Orders> ordersList) {
    //获得当前用户id
//        Long userId = BaseContext.getCurrentId();
//        Long userId = Long.valueOf("1538364171261296641");//测试
//        //查询当前用户的购物车数据
//        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(ShoppingCart::getUid,userId);//用户id
//        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);
//
//        if(shoppingCarts == null || shoppingCarts.size() == 0){
//            throw new CustomException("购物车为空，不能下单");//自定义异常
//        }
//
//        //查询用户数据
//        User user = userService.getById(userId);
//
//        //查询地址数据
//        Long addressBookId = orders.getAddressBookId();
//        AddressBook addressBook = addressBookService.getById(addressBookId);
//        if(addressBook == null){
//            throw new CustomException("用户地址信息有误，不能下单");//自定义异常
//        }
//
//        long orderId = IdWorker.getId();//订单号--md插件提供一组id的自动生成
//
//        AtomicInteger amount = new AtomicInteger(0);//原子操作类型，在高并发中保证线程安全
//
//        LambdaQueryWrapper<User> sellerWrapper = new LambdaQueryWrapper<>();
//        LambdaQueryWrapper<Goods> sellGoodsWrapper = new LambdaQueryWrapper<>();
//
//        //为了插入订单详细信息，需要查询出具体商品基本信息（名称、数量、单价等） orderdetail
//        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
//            OrderDetail orderDetail = new OrderDetail();
//            orderDetail.setOid(orderId);//订单id
//            orderDetail.setNumber(item.getNumber());
//            orderDetail.setGid(item.getGid());
//            orderDetail.setName(item.getName());
//            orderDetail.setImage(item.getImage());
//            orderDetail.setAmount(item.getAmount());
//            //根据商品表找出卖家id，再根据卖家id找到卖家名称
//            String seller_name = getSellerName(sellerWrapper,sellGoodsWrapper,item);
//            orderDetail.setSellerName(seller_name);
//            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());//从零开始，线程安全的累加
//
//            return orderDetail;
//        }).collect(Collectors.toList());
//
//        orders.setId(orderId);
//        orders.setOrderTime(LocalDateTime.now());//下单时间
//        orders.setCheckoutTime(LocalDateTime.now());//结账时间
//        orders.setStatus(2);
//        //BigDecimal()用来对超过16位有效位的数进行精确的运算
//        orders.setAmount(new BigDecimal(amount.get()));//总金额，防止浮点数计算时精度丢失
//        orders.setUid(userId);
//        orders.setNumber(String.valueOf(orderId));//订单编号
//        orders.setUname(user.getName());
//        orders.setConsignee(addressBook.getConsignee());
//        orders.setPhone(addressBook.getPhone());
//        orders.setAddress((addressBook.getDetail() == null ? "" : addressBook.getDetail()));
//        //向订单表插入数据，一条数据
//        this.save(orders);
//
//        //向订单明细表插入数据，批量插入多条数据
//        orderDetailService.saveBatch(orderDetails);
//
//        //清空购物车数据
//        shoppingCartService.remove(wrapper);
//    }
}
